/*
太原学院计算机技术系(C)版权所有。
 * 
 */
package cn.edu.tyu.fiance.thingstype.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.tyu.finance.util.DbUtil;
import cn.edu.tyu.finance.util.StringUtil;

/**
 添加用户
 * @author 田丹云
 * 
 */
@WebServlet("/AddUserServlet")// 和网页上的action要一样 
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	处理网页发来的get请求 另一个是post
	 * @param request 请求对象
	 * @param response 响应对象
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.接收网页传来的数据
		String uname=request.getParameter("username");//大小写要一直且不能有空格
		String upsw=request.getParameter("userpsw");
		String upswMD5 =StringUtil.getMD5(upsw);//加密
		//2.连接数据库把接收到的数据存储在数据库里
		Connection conn = null;//连接之前变量声明
		PreparedStatement pstmt=null;
		int flag=0;
		conn =DbUtil.getConnection();
		String sql ="INSERT INTO users VALUES(?,?,?)";//创建表
		try {
			pstmt=conn.prepareStatement(sql);//JDBC技术
			pstmt.setString(1, (int)(Math.random()*1000)+"");//赋值方式 产生随机数[0,1)  ""就是变成字符型的
			pstmt.setString(2, uname); //上边建的变量
			pstmt.setString(3, upswMD5); //上边建的变量
			flag=pstmt.executeUpdate();//下达执行命令 数据库执行
			if(flag==0)
			{
				response.sendRedirect("fail.jsp");
			}
			else {
				response.sendRedirect("ok.jsp");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
		//3.关闭数据库资源
			DbUtil.backConn(conn, pstmt, null);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	处理网页发来的post请求 另一个是get
	 * @param request 请求对象
	 * @param response 响应对象
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}